//
//  NSObject+Extension.swift
//  Swift-Categary
//
//  Created by lantaiyuan on 2017/9/11.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

import Foundation
import UIKit

extension NSObject {
    //mark---对象属性处理
    //获取对象所有的属性名称
    func allProoertyNames() -> [String] {
        var count :UInt32 = 0
        let propertys = class_copyPropertyList(self.classForCoder, &count)
        var propertyNames:[String] = []
        
        //swift中类型是很严格的,必须转化为统一类型
        for i in 0..<Int(count) {
            // UnsafeMutablePointer<objc_property_t>是
            // 可变指针，因此properties就是类似数组一样，可以
            // 通过下标获取
            let property = propertys![i]
            let name = property_getName(property)
            
            //转换成字符串
            let propertyName = String(utf8String:name!)
            propertyNames.append(propertyName!)
        }
        // 释放内存，否则C语言的指针很容易成野指针的
        free(propertys)
        return propertyNames
    }
    //获取所有对象的所有属性名称和值
    func allPropertys() -> [String : Any?] {
        var dict:[String:Any?] = [String:Any?]()
        var count:UInt32 = 0
        
        let properties = class_copyPropertyList(self.classForCoder, &count)
        for i in 0..<Int(count) {
            //获取属性名称
            let property = properties?[i]
            let name = property_getName(property)
            let propertyName = String(utf8String: name!)
            
            if !(propertyName?.isEmpty)! {
                //获取value数据
                let propertyValue = self.value(forKey: propertyName!)
                dict[propertyName!] = propertyValue
            }
        }
        return dict
    }
}
